package com.example.fangwei.utilsapp.retrofit.retrofit_request_response;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by fangwei on 2017/10/11.
 */

public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson mGson;//gson对象
    private final TypeAdapter<T> adapter;

    /**
     * 构造器
     */
    public JsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.mGson = gson;
        this.adapter = adapter;
    }

    /**
     * 转换
     *
     * @param responseBody
     * @return
     * @throws IOException
     */
    @Override
    public T convert(ResponseBody responseBody) throws IOException {

//        String response = responseBody.string();
//
//        BaseEntity baseEntity = mGson.fromJson(response, BaseEntity.class);
//        return (T) response;
        JsonReader jsonReader = mGson.newJsonReader(responseBody.charStream());
        try {
            return adapter.read(jsonReader);
        } finally {
            responseBody.close();
        }

    }

}
